/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package user.permissions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.inject.Named;
import javax.enterprise.context.Dependent;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import system.general.Logged;

/**
 *
 * @author James
 */
@Named(value = "sessionFilter")
@Dependent
public class SessionFilter implements Filter {

    private ArrayList<String> urlList;
    //Alamacenara la ruta actual despues de ser evaluada
    private String url_ant = "";

    /**
     * Creates a new instance of SessionFilter
     */
    public SessionFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String urls = filterConfig.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");

        urlList = new ArrayList<String>();

        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken().trim());

        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // la ruta del el servidor 
        String url = request.getServletPath();
        //la ruta hacia donde vamos
        String url_act = request.getRequestURI();
        boolean allowedRequest = false;

        if (urlList.contains(url)) {
            allowedRequest = true;
        }

        if (!allowedRequest) {
            HttpSession session = request.getSession(false);
            Logged logged = (Logged) session.getAttribute("logged");
            //limpia las variables si cambiamos de modulo comprobamos si las rutas son 
            //= es que se esta refrescando la misma pagina
             if (!url_act.equals(url_ant)) {
              logged.clearMenu();
           }
            this.url_ant = url_act;
            if (logged.getLoggedName().isEmpty()) {
                response.sendRedirect(request.getContextPath() + "/faces/home.xhtml");
            }
        }

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}
